package cn.xy.commons.util;

import cn.xy.commons.bean.ZipFile;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩包生成工具
 *
 *  @author xy
 */
@Slf4j
public class ZipUtil {

    private ZipUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 将多个文件生成一个压缩包
     *
     * @return 压缩包文件流
     */
    public static byte[] generateZip(List<ZipFile> zipFileList) {
        // 生成多张条形码压缩包
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        for (ZipFile zipFile : zipFileList) {
            try {
                ZipEntry zipEntry = new ZipEntry(zipFile.getFilename());
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write(zipFile.getFileBytes());
            } catch (Exception e) {
                log.error("zip generate error: ", e);
                return new byte[0];
            }
        }
        try {
            zipOutputStream.close();
        } catch (IOException e) {
            log.error("zipOutputStream close error: ", e);
            return new byte[0];
        }
        try {
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            log.error("byteArrayOutputStream close error: ", e);
            return new byte[0];
        }
        return byteArrayOutputStream.toByteArray();
    }

}
